package com.chixing.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Component
class DedaLetterListener {

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "Q2", durable = "true"),
            exchange = @Exchange(value = "exchange"),
            key = "msg.*"))
    @RabbitHandler
    public void consumeDelayMsg(@Payload String msg, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        //消费者消费
        System.out.println("repeat msg is :" + msg + ",收到消息时间:" + new Date());

        //手动签收
        channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);
    }
/*
    // deliveryTag:该消息的index
// multiple：是否批量.true:将一次性ack所有小于deliveryTag的消息。
    public void basicAck(long deliveryTag, boolean multiple)

    //deliveryTag:该消息的index
//multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
//requeue：是否重新入队列
    public void basicNack(long deliveryTag, boolean multiple, boolean requeue)
*/

    // 监听死信队列
    @RabbitListener(queues = "dle-queue")
    public void deadLetterQueue(String msg, Channel channel, Message message) throws IOException {
        System.out.println("死信队列消费消息:" + msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
